<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--表单组件-->

      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="店铺名称">
          <el-select
            v-model="queryParams.shopId"
            clearable
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in shopInfoList"
              :key="item.shopId"
              :label="item.shopName"
              :value="item.shopId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备编码">
          <el-input
            v-model="queryParams.deviceCode"
            placeholder="请输入设备编码"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select
            v-model="queryParams.deviceTypeId"
            clearable
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in deviceTypeList"
              :key="item.deviceTypeKey"
              :label="item.deviceTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="handleQuery">搜索</el-button>
          <el-button size="default" @click="resetQuery">重置</el-button>
          <el-button type="primary" size="default" @click="handleDistribution">分配设备</el-button>
          <el-button type="primary" size="default" @click="handleRelieveDevice">解绑设备</el-button>
        </el-form-item>
      </el-form>
      <!--表格渲染-->
      <el-table v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="设备编码" prop="deviceCode" />
        <el-table-column label="设备名称" prop="deviceName" width="150px" />
        <el-table-column label="设备类型" prop="deviceTypeId">
          <template #default="scope">
            {{ formatDeviceType(scope.row.deviceTypeId) }}
          </template>
        </el-table-column>
        <el-table-column label="硬件地址" prop="deviceMac" width="160px" />
        <el-table-column label="设备状态" prop="isStatus">
          <template #default="scope">
            {{
              formatDictMap('DEVICE_STATUS').find((item) => item.value == scope.row.isStatus).label
            }}
          </template>
        </el-table-column>
        <el-table-column label="网络状态" prop="netStatus">
          <template #default="scope">
            {{
              formatDictMap('DEVICE_NET_STATUS').find((item) => item.value == scope.row.netStatus)
                .label
            }}
            <!-- <dict-tag :options="dict.type.DEVICE_NET_STATUS" :value="scope.row.netStatus" /> -->
          </template>
        </el-table-column>
        <el-table-column label="软件版本号" prop="version" />
        <el-table-column label="固件版本名称" prop="firmware" />
        <!-- <el-table-column label="设备IP" prop="localIp"  width="120px"/> -->
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="创建时间" prop="createTime" width="150px" />
        <el-table-column label="店铺名称" prop="shopName" width="150px" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button @click="terminalSet(scope.row)" link type="primary" size="small"
              >终端设置</el-button
            >
            <el-button @click="handleDelete(scope.row)" link type="primary" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="total > 0"
        :total="total"
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        @change="getList"
      />
    </div>
    <!-- <GroupDialog :dialog.sync="groupDialog" @close="groupDialog = false" @success="(row)=>{formData.deviceGroupId = row.id; formData.deviceGroupName = row.deviceGroupName; }"/> -->

    <!--分配设备  -->
    <el-dialog
      title="分配设备"
      v-model="dialogDistribution"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      width="50%"
    >
      <el-form
        :model="queryShopParams"
        ref="queryDistributionForm"
        :inline="true"
        v-show="loadingDistribution"
        label-width="68px"
      >
        <el-form-item label="店铺名称">
          <el-input
            v-model="queryShopParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="店铺编码">
          <el-input
            v-model="queryShopParams.shopCode"
            placeholder="请输入店铺编码"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="handleShopQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetShopQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loadingTable"
        :data="shopList"
        highlight-current-row
        @current-change="handleCurrentChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="店铺编码" prop="shopCode" />
        <el-table-column label="店铺名称" prop="shopName" />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            {{
              formatDictMap('sys_shop_status').find((item) => item.value == scope.row.status).label
            }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="total > 0"
        :total="total"
        v-model:current-page="shopPage.pageNum"
        v-model:page-size="shopPage.pageSize"
        @change="getShopList"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogDistribution = false">取 消</el-button>
          <el-button type="primary" @click="assignDevices">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 终端设备 初始化设备信息 -->
    <DialogDefaultTerminal
      :dialog="defaultTerminalDialog"
      :deviceId="deviceId"
      @close="defaultTerminalDialog = false"
      v-if="defaultTerminalDialog"
      @submit="onSubmitDefaultSetting"
    />

    <!-- 终端设备 4G盒子 -->
    <DialogBoxTerminal
      :dialog="boxTerminalDialog"
      :deviceId="deviceId"
      @close="boxTerminalDialog = false"
      v-if="boxTerminalDialog"
      @submit="onSubmitBoxSetting"
    />

    <!-- 终端设备 POS机 -->
    <DialogPosTerminal
      :dialog="posTerminalDialog"
      :deviceId="deviceId"
      @close="posTerminalDialog = false"
      v-if="posTerminalDialog"
      @submit="onSubmitPosSetting"
    />

    <!-- 终端设备 收银机 -->
    <DialogCashierTerminal
      :dialog="cashierTerminalDialog"
      :deviceId="deviceId"
      @close="cashierTerminalDialog = false"
      v-if="cashierTerminalDialog"
      @submit="onSubmitCashierSetting"
    />

    <!-- 终端设备 闸机 -->
    <DialogGateTerminal
      :dialog="gateTerminalDialog"
      :deviceId="deviceId"
      @close="gateTerminalDialog = false"
      v-if="gateTerminalDialog"
      @submit="onSubmitGateSetting"
    />

    <!-- 终端设备 兑币机 -->
    <DialogCoinTerminal
      :dialog="coinTerminalDialog"
      :deviceId="deviceId"
      @close="coinTerminalDialog = false"
      v-if="coinTerminalDialog"
      @submit="onSubmitCoinSetting"
    />

    <!-- 终端设备 人脸机 -->
    <DialogFaceTerminal
      :dialog="faceTerminalDialog"
      :deviceId="deviceId"
      @close="faceTerminalDialog = false"
      v-if="faceTerminalDialog"
      @submit="onSubmitFaceSetting"
    />

    <!-- 终端设备 存票机 -->
    <DialogDepositLotteryTerminal
      :dialog="depositLotteryTerminalDialog"
      :deviceId="deviceId"
      @close="depositLotteryTerminalDialog = false"
      v-if="depositLotteryTerminalDialog"
      @submit="onSubmitDepositLotterySetting"
    />

    <!-- 终端设备 存币机 -->
    <DialogDepositCoinTerminal
      :dialog="depositCoinTerminalDialog"
      :deviceId="deviceId"
      @close="depositCoinTerminalDialog = false"
      v-if="depositCoinTerminalDialog"
      @submit="onSubmitDepositCoinSetting"
    />

    <!-- 终端设备 票务机 -->
    <DialogEntranceTicketTerminal
      :dialog="entranceTicketTerminalDialog"
      :deviceId="deviceId"
      @close="entranceTicketTerminalDialog = false"
      v-if="entranceTicketTerminalDialog"
      @submit="onSubmitEntranceTicketSetting"
    />
  </div>
</template>

<script>
  import {
    deviceList,
    saveDevice,
    deleteDevice,
    getDeviceDetails,
    updateDevice,
    updateAssignDevices,
    relieveDevice,
  } from '@/api/device/device.js';
  import { deviceTypeList } from '@/api/device/type.js';
  import { getShopAllList, getShopList } from '@/api/shop/shop.js';
  import DialogBoxTerminal from './dialogBoxTerminal.vue';
  import DialogPosTerminal from './dialogPosTerminal.vue';
  import DialogCashierTerminal from './dialogCashierTerminal.vue';
  import DialogDefaultTerminal from './dialogDefaultTerminal.vue';
  import DialogGateTerminal from './dialogGateTerminal.vue';
  import DialogCoinTerminal from './dialogCoinTerminal.vue';
  import DialogFaceTerminal from './dialogFaceTerminal.vue';
  import DialogDepositLotteryTerminal from './dialogDepositLotteryTerminal.vue';
  import DialogDepositCoinTerminal from './dialogDepositCoinTerminal.vue';
  import DialogEntranceTicketTerminal from './dialogEntranceTicketTerminal.vue';
  import { getDictOptions } from '@/utils/dict';
  import { ElMessage, ElMessageBox } from 'element-plus';

  export default {
    name: 'DeviceList',
    dicts: [
      'DEVICE_STATUS',
      'DEVICE_NET_STATUS',
      'DEVICE_EFFECT_STATUS',
      'DEVICE_ISSUED_STATUS',
      'sys_shop_status',
    ],
    components: {
      DialogBoxTerminal,
      DialogPosTerminal,
      DialogDefaultTerminal,
      DialogCashierTerminal,
      DialogGateTerminal,
      DialogCoinTerminal,
      DialogFaceTerminal,
      DialogDepositLotteryTerminal,
      DialogDepositCoinTerminal,
      DialogEntranceTicketTerminal,
    },
    data() {
      return {
        loading: false,
        loadingDistribution: false,
        loadingTable: false,
        single: true,
        multiple: true,
        tableDataList: [],
        addDialog: false,
        dialogDistribution: false,
        title: '新增设备',
        currentShopId: '',
        formData: {
          status: -1,
          isPostage: 0,
          productName: '',
          stock: 0,
          price: 0,
          otPrice: 0,
          costPrice: 0,
        },
        total: 0,
        page: {
          pageNum: 1, // 当前页数
          pageSize: 10, // 每页显示多少条
        },
        shopPage: {
          pageNum: 1, // 当前页数
          pageSize: 10, // 每页显示多少条
        },
        queryParams: {},
        queryShopParams: {
          shopCode: undefined,
          shopName: undefined,
        },
        showSearch: true,
        rules: {
          deviceCode: [{ required: true, message: '设备编码不可为空！', trigger: 'blur' }],
          deviceName: [{ required: true, message: '设备名称不可为空！', trigger: 'blur' }],
          deviceTypeId: [{ required: true, message: '设备类型不可为空！', trigger: 'blur' }],
          isStatus: [{ required: true, message: '设备状态不可为空！', trigger: 'blur' }],
          isIssued: [{ required: true, message: '同步配置不可为空！', trigger: 'blur' }],
        },
        deviceTypeList: [],
        shopInfoList: [],
        shopList: [],
        edit: false,
        boxTerminalDialog: false,
        boxTerminalLoading: false,
        posTerminalDialog: false,
        posTerminalLoading: false,
        cashierTerminalDialog: false,
        cashierTerminalLoading: false,
        defaultTerminalDialog: false,
        defaultTerminalLoading: false,
        gateTerminalDialog: false,
        gateTerminalLoading: false,
        coinTerminalDialog: false,
        coinTerminalLoading: false,
        faceTerminalDialog: false,
        faceTerminalLoading: false,
        depositLotteryTerminalDialog: false,
        depositLotteryTerminalLoading: false,
        depositCoinTerminalDialog: false,
        depositCoinTerminalLoading: false,
        entranceTicketTerminalDialog: false,
        entranceTicketTerminalLoading: false,
        deviceId: '',
        ids: null,
        dict_map_DEVICE_STATUS: null,
      };
    },
    created() {
      this.getList();
      deviceTypeList({}).then((res) => {
        this.deviceTypeList = res;
      });
      getShopAllList({}).then((res) => {
        this.shopInfoList = res;
      });
    },
    methods: {
      // 格式化字典
      formatDictMap(dictEnum) {
        return getDictOptions(dictEnum);
      },
      // 格式化设备
      formatDeviceType(typeId) {
        if (!this.deviceTypeList) {
          return '';
        }
        let deviceTypeName = '';
        this.deviceTypeList.forEach((res) => {
          if (res.id == typeId) {
            deviceTypeName = res.deviceTypeName;
            return true;
          }
        });
        return deviceTypeName;
      },
      formatDeviceTypeKey(typeId) {
        if (!this.deviceTypeList) {
          return '';
        }
        let deviceTypeKey = '';
        this.deviceTypeList.forEach((res) => {
          if (res.id == typeId) {
            deviceTypeKey = res.deviceTypeKey;
            return true;
          }
        });
        return deviceTypeKey;
      },
      selectQueryType() {
        this.queryParams.queryContent = undefined;
      },
      /**
       * 图片上传回调
       */
      onImageUpload() {},
      /** 搜索按钮操作 */
      handleQuery() {
        this.page.pageNum = 1;
        this.getList();
      },
      // 查询店铺列表
      handleShopQuery() {
        this.shopPage.pageNum = 1;
        this.loadingDistribution = true;
        this.getShopList();
        this.dialogDistribution = true;
      },
      // 查询店铺列表
      getShopList() {
        getShopList(this.shopPage, this.queryShopParams)
          .then((response) => {
            this.shopList = response.records;
            this.total = response.total;
            this.loadingTable = false;
          })
          .catch(() => {
            this.loadingTable = false;
          });
      },
      /**
       * 搜索重置
       */
      resetQuery() {
        this.queryParams = {
          queryType: 'ITEM_ID',
          queryContent: undefined,
        };
        this.getList();
      },
      // 查询店铺列表
      handleDistribution() {
        if (this.ids == null) {
          ElMessage({
            message: '请先勾选终端设备！',
            type: 'warning',
          });
        } else {
          this.loadingDistribution = true;
          getShopList(this.shopPage, this.queryShopParams)
            .then((response) => {
              this.shopList = response.records;
              this.total = response.total;
              this.loadingTable = false;
            })
            .catch(() => {
              this.loadingTable = false;
            });
          this.dialogDistribution = true;
        }
      },
      handleRelieveDevice() {
        if (this.ids == null) {
          ElMessage({
            message: '请先勾选终端设备！',
            type: 'warning',
          });
        } else {
          const ids1 = this.ids;
          ElMessageBox.confirm('是否确认解绑终端设备？')
            .then(function () {
              return relieveDevice({ deviceIdList: JSON.stringify(ids1) });
            })
            .then(() => {
              this.getList();
              ElMessage({
                message: '请先勾选终端设备！',
                type: 'success',
              });
            })
            .catch(() => {});
        }
      },
      // 搜索重置
      resetShopQuery() {
        this.queryShopParams = {
          shopCode: undefined,
          shopName: undefined,
        };
      },
      // 获取选中的店铺
      handleCurrentChange(val) {
        this.currentShopId = val.shopId;
      },
      // 提交表单
      submitForm() {
        this.loading = true;
        if (this.formData.id) {
          updateDevice(this.formData).then(() => {
            this.dialogDistribution = false;
            this.loading = false;
            this.addDialog = false;
            this.getList();
          });
          return;
        }
        saveDevice(this.formData).then(() => {
          this.loading = false;
          this.addDialog = false;
          this.getList();
        });
      },
      // 新增设备
      handleAdd() {
        this.reset();
        this.addDialog = true;
        this.edit = false;
        this.formData = {};
        this.title = '添加设备';
      },
      // 表单重置
      reset() {},
      // 分配设备
      assignDevices() {
        updateAssignDevices({
          deviceIdList: JSON.stringify(this.ids),
          shopId: this.currentShopId,
        }).then(() => {
          ElMessage({
            message: '分配设备成功！',
            type: 'success',
          });
          this.dialogDistribution = false;
          this.getList();
        });
      },
      //终端设置
      terminalSet(row) {
        const deviceTypeId = row.deviceTypeId;
        const deviceTypeKey = this.formatDeviceTypeKey(deviceTypeId);
        const id = row.id;
        if (deviceTypeKey == 'BM') {
          this.boxTerminalDialog = true;
          this.boxTerminalLoading = true;
        } else if (deviceTypeKey == 'PM') {
          this.posTerminalDialog = true;
          this.posTerminalLoading = true;
        } else if (deviceTypeKey == 'CM') {
          this.cashierTerminalDialog = true;
          this.cashierTerminalLoading = true;
        } else if (deviceTypeKey == 'GM') {
          this.gateTerminalDialog = true;
          this.gateTerminalLoading = true;
        } else if (deviceTypeKey == 'CEM') {
          this.coinTerminalDialog = true;
          this.coinTerminalLoading = true;
        } else if (deviceTypeKey == 'FD') {
          this.faceTerminalDialog = true;
          this.faceTerminalLoading = true;
        } else if (deviceTypeKey == 'TSM') {
          this.depositLotteryTerminalDialog = true;
          this.depositLotteryTerminalLoading = true;
        } else if (deviceTypeKey == 'CSM') {
          this.depositCoinTerminalDialog = true;
          this.depositCoinTerminalLoading = true;
        } else if (deviceTypeKey == 'TM') {
          this.entranceTicketTerminalDialog = true;
          this.entranceTicketTerminalLoading = true;
        } else if (deviceTypeId == 0) {
          this.defaultTerminalDialog = true;
          this.defaultTerminalLoading = true;
        } else {
          ElMessage({
            message: '其他设备类型暂未开放设置！',
            type: 'warning',
          });
        }
        this.deviceId = id;
      },
      /** 查询分类列表 */
      getList() {
        this.loading = true;
        deviceList(this.page, { ...this.page, ...this.queryParams })
          .then((response) => {
            this.tableDataList = response.records;
            this.total = response.total;
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });

        // this.tableDataList = res.data.records;
        this.loading = false;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id;
        if (!id) {
          ElMessage({
            message: '请选择需要修改的信息！',
            type: 'warning',
          });
          return;
        }
        getDeviceDetails(id).then((res) => {
          this.formData = res.data;
          this.addDialog = true;
          this.edit = true;
          this.title = '修改设备';
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id;
        ElMessageBox.confirm('是否确认删除终端设备，删除后不可恢复？')
          .then(function () {
            return deleteDevice(id);
          })
          .then(() => {
            this.getList();
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
            this.$modal.msgSuccess('删除成功');
          })
          .catch(() => {});
      },
      onSubmitDefaultSetting() {
        this.defaultTerminalDialog = false;
        this.getList();
      },
      onSubmitBoxSetting() {
        this.boxTerminalDialog = false;
        this.getList();
      },
      onSubmitPosSetting() {
        this.posTerminalDialog = false;
        this.getList();
      },
      onSubmitCashierSetting() {
        this.cashierTerminalDialog = false;
        this.getList();
      },
      onSubmitGateSetting() {
        this.gateTerminalLoading = false;
        this.getList();
      },
      onSubmitCoinSetting() {
        this.coinTerminalLoading = false;
        this.getList();
      },
      onSubmitFaceSetting() {
        this.faceTerminalLoading = false;
        this.getList();
      },
      onSubmitDepositLotterySetting() {
        this.depositLotteryTerminalLoading = false;
        this.getList();
      },
      onSubmitDepositCoinSetting() {
        this.depositCoinTerminalLoading = false;
        this.getList();
      },
      onSubmitEntranceTicketSetting() {
        this.entranceTicketTerminalLoading = false;
        this.getList();
      },
    },
  };
</script>

<style scoped></style>
